﻿using System;
using Markdig;
using System.Windows.Forms;

namespace Easily._02_Form.KimiAI
{
    public partial class KimiHelper : Form
    {
        KimiApiService Kimi;

        public KimiHelper()
        {
            InitializeComponent();
        }

        private string response;
        private int currentIndex = 0;
        private bool isTyping = false;
        private async void sendMessageToKimi_btn_Click(object sender, EventArgs e)
        {
            if (Globaldefine.KimiAPIKey == "")
            {
                MessageBox.Show("请先在设置中输入Kimi API Key！");
                return;
            }

            string message = userAsk_tbx.Text;
            if (message == "")
            {
                return;
            }
            if (Kimi == null)
                Kimi = new KimiApiService(Globaldefine.KimiAPIKey);
            else if (Kimi._apiKey != Globaldefine.KimiAPIKey)
            {
                Kimi._apiKey = Globaldefine.KimiAPIKey;
            }

            KimiReplied_tbx.Text += "你: " + message + "\n";
            userAsk_tbx.Text = "";
            KimiReplied_tbx.Text += "Kimi正在思考中...\n";
            response = await Kimi.GetResponseAsync(message);
            var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
            response = Markdown.ToPlainText(response, pipeline);
            if (response == null || response == "")
            {
                MessageBox.Show("Kimi API 调用失败, 请检查网络连接或API Key是否正确！");
                return;
            }

            isTyping = true;
            currentIndex = 0;
            RepliedTimer.Start();
        }

        private void apiKey_btn_Click(object sender, EventArgs e)
        {
            APIKeyForm apiKeyForm = new APIKeyForm();
            apiKeyForm.ShowDialog();
        }

        private void RepliedTimer_Tick(object sender, EventArgs e)
        {
            if (isTyping && currentIndex < response.Length)
            {
                KimiReplied_tbx.Text +=
                    response[currentIndex++];
            }
            else
            {
                KimiReplied_tbx.Text += "\n";
                isTyping = false;
                RepliedTimer.Stop();
            }
        }

        private void clearReplied_Click(object sender, EventArgs e)
        {
            if (Kimi == null)
                return;
            if (MessageBox.Show("确定开始新的对话吗？", "提示", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                KimiReplied_tbx.Text = "";
                userAsk_tbx.Text = "";
                currentIndex = 0;
                isTyping = false;
                response = "";
                RepliedTimer.Stop();
                Kimi.ClearHistory();
            }
        }
    }
}
